
package edu.hm.vss.diningphilosophers;


public class Fork {

    private forkIs is_dirty = forkIs.clean;
    private int fork_id;
    private boolean side;
    DiningTable Table;

    Fork( int t_fork_id, boolean init_side, DiningTable t_Table ) {
        fork_id = t_fork_id;
        side = init_side;
        Table = t_Table;
    }

    public synchronized void get() {
       //s System.out.println("Get forkId: " + fork_id + " " + (is_dirty ? "dirty" : "clean") + " side: " + side);
        while( is_dirty == forkIs.clean)
        {
            try {
                wait();
            } catch( InterruptedException e ) {}
        }
        is_dirty = forkIs.clean;
        side = !side;
        Table.updateFork( fork_id, side, forkIs.clean );
        notifyAll();
    }

    public synchronized void give() {
        //System.out.println("Give forkId: " + fork_id + " " + (is_dirty ? "dirty" : "clean") + " side: " + side);
        is_dirty = forkIs.dirty;
        Table.updateFork( fork_id, side, forkIs.dirty );
        notifyAll();
        while( is_dirty ==  forkIs.dirty)
        {
            try {
                wait();
            } catch( InterruptedException e ) {}
        }
    }

}
